package cn.yeyiu.netonlinevideo.parser.video;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.parser.Parser;
import cn.yeyiu.netonlinevideo.viewmodel.DataListViewModel;
import cn.yeyiu.util.NetUtil;
import cn.yeyiu.util.bean.MediaData;
import cn.yeyiu.util.bean.VideoInfo;

public class ZBSParser extends Parser {

    public ZBSParser(SourceData source) {
        super(source);
    }

    private String postUrl(String vtype, int pageIndex) {

        JSONObject body = new JSONObject();
        body.put("action", "getvideos");
        body.put("vtype", vtype);
        body.put("pageindex", String.valueOf(pageIndex + 1));
        body.put("source.pageSize", String.valueOf(source.pageSize));
        body.put("tags", "全部");

        String apiUrl = "https://apizbsp.com/web/abcdefg.ashx";
        return NetUtil.postByUrl(apiUrl, body, false);
    }

    @Override
    public Object getBaseData(String type, int pageIndex) {
        String vtype = getArgv(type, "vtype");
        String json = postUrl(vtype, pageIndex);
        return JSONObject.parseObject(json);
    }

    @Override
    public int getMaxCount(Object data) {
        JSONObject jo = (JSONObject) data;
        return jo.getIntValue("pagecount");
    }

    @Override
    public List<MediaData> getDataList(Object data, String type) {
        Map<String, String> map = getArgvMap(type);
        String root = map.get("root");
        String vtypeArgv = map.get("vtypeArgv");
        vtypeArgv = vtypeArgv == null ? "" : vtypeArgv;

        JSONObject jo = (JSONObject) data;
        JSONArray jsonArray = jo.getJSONArray("videos");

        List<MediaData> videoInfos = new ArrayList<>();
        MediaData mediaData;
        VideoInfo videoInfo;
        for (int i = 0; i < jsonArray.size(); ++i) {
            videoInfo = new VideoInfo();
            mediaData = new MediaData();

            videoInfo.code = source.code;
            videoInfo.type = type;
            videoInfo.title = jsonArray.getJSONObject(i).getString("title");
            videoInfo.picSrc = jsonArray.getJSONObject(i).getString("coverimg");
            videoInfo.videoSrc = "https://" + root + ".34885.xyz/" + vtypeArgv + jsonArray.getJSONObject(i).getString("vurl");

            mediaData.wrap(videoInfo);
            videoInfos.add(mediaData);
        }
        return videoInfos;
    }
}
